package com.wngbms.aop.interceptor;

import com.wngbms.aop.staticproxy.EchoService;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

public class AopInterceptor implements InvocationHandler {

    EchoService echoService;
    BeforeInterceptor beforeInterceptor;
    AfterReturnInterceptor afterReturnInterceptor;
    FinallyInterceptor finallyInterceptor;
    ExceptionInterceptor exceptionInterceptor;

    public AopInterceptor(EchoService echoService, BeforeInterceptor beforeInterceptor, AfterReturnInterceptor afterReturnInterceptor, FinallyInterceptor finallyInterceptor) {
        this.echoService = echoService;
        this.beforeInterceptor = beforeInterceptor;
        this.afterReturnInterceptor = afterReturnInterceptor;
        this.finallyInterceptor = finallyInterceptor;
    }

    public AopInterceptor(EchoService echoService, BeforeInterceptor beforeInterceptor, AfterReturnInterceptor afterReturnInterceptor, FinallyInterceptor finallyInterceptor, ExceptionInterceptor exceptionInterceptor) {
        this.echoService = echoService;
        this.beforeInterceptor = beforeInterceptor;
        this.afterReturnInterceptor = afterReturnInterceptor;
        this.finallyInterceptor = finallyInterceptor;
        this.exceptionInterceptor = exceptionInterceptor;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        String echo = null;
        try {
            Long startTime = (Long) beforeInterceptor.before(proxy, method, args);
            echo = echoService.echo((String) args[0]);
            Long endTime = (Long) afterReturnInterceptor.after(proxy, method, args, echo);
        } catch (Exception e) {
            exceptionInterceptor.intercept(proxy, method, args, e);
        } finally {
            Long cost = (Long) finallyInterceptor.finalize(proxy, method, args, echo);
            System.out.println("cost:" + cost);
        }
        return echo;
    }
}
